package com.iflytek.springboot_medicine.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.iflytek.springboot_medicine.entity.User;
import com.iflytek.springboot_medicine.service.UserRepository;
import com.iflytek.springboot_medicine.util.JwtUtil;
import com.iflytek.springboot_medicine.util.RedisUtil;
import jakarta.persistence.criteria.Root;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl{

    private final UserRepository userRepository;
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    /**
     * 用户登录
     */
    public User login(String username, String password) {
        try {
            log.debug("Attempting login for user: {}", username);
            User user = findByUsernameAndPassword(username, password);
            if (user != null) {
                log.debug("Login successful for user: {}", username);
                return user;
            }
            log.warn("Login failed for user: {} - Invalid credentials", username);
            return null;
        } catch (Exception e) {
            log.error("Login error for user: {} - {}", username, e.getMessage());
            return null;
        }
    }

    /**
     * 用户注册
     */
    public String register(String username, String password, String role) {
        User u = findByUsernameAndPassword(username,password);
        if (u != null) {
            return "账号已存在，不能再次创建";
        }
        String name = "new" + username;
        String email = Math.random()+"@example.com";
        String phone = Math.random()+"";
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setName(name);
        user.setEmail(email);
        user.setRole(role);
        user.setPhone(phone);
        userRepository.save(user);
        return "注册成功";
    }

    /**
     * 根据账号密码查询
     */
    public User findByUsernameAndPassword(String username, String password) {
        if (!"".equals(username) || username != null) {
            return userRepository.findByUsernameAndPassword(username,password);
        }
        return null;
    }

    /**
     *分页查询
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Page<User> findUsers(String name, int pageNum, int pageSize) {
        // 构建分页请求
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        // 执行分页查询
        return userRepository.findByName(name, pageable);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    public User addUser(User user) {
        return userRepository.save(user);
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    public User updateUser(User user) {
        User dbuser = userRepository.findByName(user.getUsername());
        return userRepository.save(dbuser);
    }


    /**
     * 更新密码
     */
    public User updatePassword(User user) {
        // 1. 根据用户名查询用户
        User dbUser = userRepository.findByName(user.getUsername());
        if (dbUser == null) {
            return null; // 用户不存在
        }

        // 2. 验证原始密码是否正确
        if (!dbUser.getPassword().equals(user.getPassword())) {
            return null; // 原始密码错误
        }

        // 4. 更新新密码
        dbUser.setPassword(user.getNewPassword());
        userRepository.save(dbUser);

        // 5. 清理Redis中的用户信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = JwtUtil.getTokenFromRequest(request);
        if (token != null) {
            RedisUtil.delete("USER:" + token);
        }

        return dbUser;
    }


    /**
     * 删除用户
     */
    public User deleteUser(int id) {
        return userRepository.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteAllInBatch(List<Integer> ids) {
        userRepository.deleteAllByIdInBatch(ids);
    }

    /**
     * 根据姓名查找
     * @param name
     * @return
     */
    public User findByUsername(String name) {
        User byName = userRepository.findByUsername(name);
        return byName;
    }

    public User findByName(String name) {
        User byName = userRepository.findByName(name);
        return byName;
    }




    /**
     * 查找所有用户，用于echarts表
     * @return
     */
    public List<User> searchAllUsers() {
        return userRepository.findAll();
    }

    public String getToken(User user) {
        Date start = new Date();
        //6小时有效时间
        long currentTime = System.currentTimeMillis() + 1000 * 60 * 60 * 6;
        Date end = new Date(currentTime);

        String token = JWT.create().withAudience(user.getUsername())
                .withIssuedAt(start)
                .withExpiresAt(end)
                .sign(Algorithm.HMAC256(user.getPassword()));

        return token;
    }


    public User findUserByUsername(String username) {
        User user1 = userRepository.findByName(username);
        System.out.println(user1);
        return user1;
    }
}
